<template>
  <view class="comments-page">
    <!-- 评论列表 -->
    <view class="comments-container">
      <!-- 根评论和回复列表 -->
      <view 
        v-for="(comment, index) in allComments" 
        :key="index" 
        class="comment-item">
        <!-- 根评论或回复 -->
        <view class="comment-main">
          <image :src="comment.userAvatar" class="user-avatar"></image>
          <view class="comment-content-wrapper">
            <view class="comment-user-info">
              <!-- 根据是否有parentName显示不同的用户信息 -->
              <text class="username" v-if="comment.parentName">
                {{ comment.userName }} 回复 {{ comment.parentName }}
              </text>
              <text class="username" v-else>{{ comment.userName }}</text>
              <text class="comment-time">{{ formatCommentTime(comment.createTime) }}</text>
            </view>
            <text class="comment-text">{{ comment.content }}</text>
            
            <!-- 评论图片 -->
            <view 
              class="comment-images" 
              v-if="comment.images && comment.images.length">
              <image 
                v-for="(img, imgIdx) in comment.images" 
                :key="imgIdx" 
                :src="img" 
                mode="aspectFill"
                class="comment-image">
              </image>
            </view>
            
            <!-- 回复按钮和回复数 -->
            <view class="comment-interaction">
              <view 
                class="reply-trigger" 
                @click="handleReplyClick(comment)">
                <text>回复</text>
                <text 
                  v-if="comment.replies && comment.replies.length" 
                  class="reply-count">
                  {{ comment.replies.length }}
                </text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 行内回复输入框 -->
        <view 
          v-if="currentReplyComment === comment && showReplyInput" 
          class="inline-reply-container"
        >
          <textarea 
            v-model="replyContent"
            placeholder="说点什么..."
            class="inline-reply-textarea"
            maxlength="200"
          ></textarea>
          <view class="inline-reply-footer">
            <text class="text-count">{{ replyContent.length }}/200</text>
            <view 
              class="submit-btn" 
              @click="submitInlineReply"
            >
              发送
            </view>
          </view>
        </view>
        
        <!-- 回复列表 -->
        <view 
          class="replies-container" 
          v-if="comment.replies && comment.replies.length">
          <view 
            class="reply-item" 
            v-for="(reply, replyIdx) in comment.replies" 
            :key="replyIdx">
            <view class="reply-content">
              <text class="reply-username">{{ reply.userName }}：</text>
              <text class="reply-text">{{ reply.content }}</text>
            </view>
            <view 
              class="reply-interaction"
              @click="handleReplyClick(comment, reply)">
              <text>回复</text>
            </view>
          </view>
        </view>
        
        <!-- 回复输入区域 -->
        <view 
          v-if="showReplyInput && currentReplyComment === comment" 
          class="reply-input-container">
          <textarea 
            v-model="replyContent"
            placeholder="说点什么..."
            maxlength="200"
            class="reply-textarea">
          </textarea>
          <view class="reply-input-footer">
            <text class="text-count">{{ replyContent.length }}/200</text>
            <button 
              @click="submitReply" 
              class="submit-btn">
              发送
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 回复弹窗 -->
    <uni-popup ref="replyPopup" type="bottom">
      <view class="reply-popup">
        <view class="reply-header">
          <text class="reply-title">
            {{ replyTarget ? `回复 ${replyTarget.userName}` : '发表评论' }}
          </text>
        </view>
        <textarea 
          v-model="replyContent" 
          placeholder="说点什么..." 
          class="reply-textarea"
          maxlength="200">
        </textarea>
        <view class="reply-footer">
          <text class="text-count">{{ replyContent.length }}/200</text>
          <button 
            @click="submitReply" 
            class="submit-btn" 
            :disabled="!replyContent.trim()">
            发送
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getCommentReplies, addCommentReply, getComments } from '../api/api.js'

export default {
  data() {
    return {
      allComments: [],
      pageInfo: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      replyContent: '',
      replyTarget: null,
      showReplyInput: false,
      currentReplyComment: null,
      commentId: ''
    }
  },
  onLoad(options) {
    // 解析传递的评论ID和评论对象
    this.commentId = options.commentId
    
    // 尝试解析传递的完整评论对象
    if (options.comment) {
      try {
        const comment = JSON.parse(decodeURIComponent(options.comment))
        console.log('接收到的完整评论对象:', comment)
        
        // 如果成功解析，直接设置根评论
        this.allComments = [comment]
        
        // 获取该评论的回复
        this.fetchRepliesList()
      } catch (error) {
        console.error('解析评论对象失败:', error)
        
        // 如果解析失败，走原有的加载逻辑
        this.loadComments()
      }
    } else {
      // 没有传递评论对象，走原有的加载逻辑
      this.loadComments()
    }
  },
  methods: {
    // 加载评论
    loadComments() {
      // 调试：打印 commentId
      console.log('当前评论ID:', this.commentId)
      
      // 直接获取回复列表，以 commentId 为根评论
      this.fetchRepliesList()
    },

    // 获取回复列表
    fetchRepliesList() {
      const params = {
        rootId: this.commentId,
        page: this.pageInfo.page,
        pageSize: this.pageInfo.pageSize
      }

      console.log('尝试获取回复列表，参数:', params)

      uni.showLoading({ title: '加载中', mask: true })

      getCommentReplies(params).then(res => {
        console.log('回复列表接口返回:', res)
        
        uni.hideLoading()
        
        if (res.code === 1) {
          const commentData = res.data.records || res.data
          console.log('回复数据:', commentData)
          
          // 添加回复，按时间排序
          if (commentData.length > 0) {
            const sortedReplies = commentData.sort((a, b) => 
              new Date(a.createTime) - new Date(b.createTime)
            )
            
            // 如果已有根评论，保持根评论在第一个
            if (this.allComments && this.allComments.length > 0) {
              this.allComments = [this.allComments[0]].concat(sortedReplies)
            } else {
              this.allComments = sortedReplies
            }
          }
          
          // 如果没有数据，显示提示
          if (this.allComments.length === 0) {
            uni.showToast({
              title: '未找到评论',
              icon: 'none'
            })
          }
        } else {
          uni.showToast({
            title: res.msg || '加载评论失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        uni.hideLoading()
        console.error('获取回复列表失败:', err)
        uni.showToast({ title: '加载失败', icon: 'none' })
      })
    },

    // 处理回复点击
    handleReplyClick(comment, replyTarget = null) {
      uni.getSystemInfo({
        success: (res) => {
          if (res.windowWidth < 768) {
            this.showReplyPopup(comment, replyTarget)
          } else {
            if (this.currentReplyComment === comment) {
              this.showReplyInput = !this.showReplyInput
            } else {
              this.currentReplyComment = comment
              this.replyTarget = replyTarget
              this.showReplyInput = true
            }
          }
        },
        fail: () => {
          this.showReplyPopup(comment, replyTarget)
        }
      })
    },

    // 显示回复弹窗
    showReplyPopup(comment, replyTarget = null) {
      this.currentReplyComment = comment
      this.replyTarget = replyTarget
      this.replyContent = ''
      this.$refs.replyPopup.open()
    },

    // 提交行内回复
    submitInlineReply() {
      this.submitReply(true)
    },

    // 提交回复
    submitReply(isInline = false) {
      if (!this.replyContent.trim()) {
        uni.showToast({
          title: '回复内容不能为空',
          icon: 'none'
        })
        return
      }

      // 获取当前登录用户信息
      const userInfo = uni.getStorageSync('userInfo')
      const currentUsername = userInfo ? userInfo.nickName : '匿名用户'

      // 调试日志：检查当前评论和根评论的详细信息
      console.log('当前登录用户信息:', userInfo)
      console.log('当前回复评论对象:', this.currentReplyComment)
      console.log('根评论列表:', this.allComments)

      const params = {
        // 始终使用第一个评论（根评论）的 ID 作为 rootId
        rootId: this.allComments[0].id,
        
        // 使用根评论的用户名作为 rootName
        rootName: this.allComments[0].username || this.allComments[0].userName || '匿名用户',
        
        // 如果有回复目标，设置 parentName 为当前评论的 username
        parentName: this.currentReplyComment.username || this.currentReplyComment.userName || '匿名用户',
        
        // 当前用户名
        userName: currentUsername,
        
        // 回复的内容
        content: this.replyContent.trim(),
        
        // 设置类型为回复
        type: 1  // 假设1代表回复
      }

      // 调试日志：检查最终传递的参数
      console.log('回复请求参数:', params)

      addCommentReply(params).then(res => {
        console.log('回复接口返回:', res)
        
        if (res.code === 1) {
          // 弹出成功提示
          uni.showToast({
            title: '回复成功',
            icon: 'success',
            duration: 1500  // 延长提示显示时间
          })

          // 立即重置所有回复相关状态
          this.replyContent = ''
          this.showReplyInput = false  // 关闭回复弹窗
          this.currentReplyComment = null
          this.replyTarget = null

          // 关闭发表评论的弹窗
          if (this.$refs.replyPopup) {
            this.$refs.replyPopup.close()
          }

          // 重新获取回复列表
          this.fetchRepliesList()
        } else {
          uni.showToast({
            title: res.msg || '回复失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        console.error('回复失败:', err)
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
      })
    },

    // 时间格式化
    formatCommentTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const now = new Date()
      const diff = now.getTime() - date.getTime()
      
      if (diff < 60000) return '刚刚'
      if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
      if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
      
      return date.toLocaleString()
    }
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.pageInfo.page = 1
    this.loadComments()
    uni.stopPullDownRefresh()
  },
  // 触底加载更多
  onReachBottom() {
    if (this.allComments.length < this.pageInfo.total) {
      this.pageInfo.page++
      this.loadComments()
    }
  }
}
</script>

<style scoped>
/* 样式与 index.vue 保持一致 */
.comments-page {
  height: 100%;
}

.comments-container {
  padding: 20rpx;
}

.comment-item {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
}

.comment-main {
  display: flex;
  align-items: flex-start;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.comment-content-wrapper {
  flex: 1;
}

.comment-user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.username {
  font-weight: bold;
  color: #333;
  font-size: 28rpx;
}

.comment-time {
  color: #999;
  font-size: 24rpx;
}

.comment-text {
  color: #333;
  font-size: 30rpx;
  line-height: 1.5;
}

.comment-images {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
}

.comment-image {
  width: 200rpx;
  height: 200rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
  border-radius: 8rpx;
}

.comment-interaction {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 10rpx;
}

.reply-trigger {
  display: inline-flex;
  align-items: center;
  color: #666;
  font-size: 24rpx;
  background-color: #f5f5f5;
  padding: 4rpx 12rpx;
  border-radius: 16rpx;
  cursor: pointer;
}

.reply-trigger text {
  margin-right: 5rpx;
}

.reply-count {
  background-color: #e0e0e0;
  border-radius: 16rpx;
  padding: 0 8rpx;
  font-size: 20rpx;
  min-width: 20rpx;
  text-align: center;
}

.replies-container {
  margin-top: 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 10rpx;
}

.reply-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #e0e0e0;
}

.reply-content {
  flex: 1;
}

.reply-username {
  color: #666;
  font-weight: bold;
  margin-right: 10rpx;
  font-size: 26rpx;
}

.reply-text {
  color: #333;
  font-size: 26rpx;
}

.replies-container .reply-interaction {
  display: inline-flex;
  align-items: center;
  color: #666;
  font-size: 24rpx;
  background-color: #f5f5f5;
  padding: 4rpx 12rpx;
  border-radius: 16rpx;
  cursor: pointer;
  margin-left: 10rpx;
}

.reply-popup {
  background-color: white;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding: 20rpx;
}

.reply-header {
  text-align: center;
  margin-bottom: 20rpx;
}

.reply-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.reply-textarea {
  width: 100%;
  height: 200rpx;
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
}

.reply-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
}

.text-count {
  color: #999;
  font-size: 24rpx;
}

.submit-btn {
  background-color: #007bff;
  color: white;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
}

.submit-btn:disabled {
  background-color: #e0e0e0;
  color: #999;
}

.inline-reply-container {
  background-color: #f5f5f5;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-top: 10rpx;
}

.inline-reply-textarea {
  width: 100%;
  min-height: 200rpx;
  background-color: white;
  border-radius: 10rpx;
  padding: 10rpx;
  margin-bottom: 10rpx;
}

.inline-reply-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.inline-reply-footer .text-count {
  color: #999;
  font-size: 24rpx;
}

.inline-reply-footer .submit-btn {
  background-color: #007bff;
  color: white;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
}

.reply-input-container {
  background-color: #f5f5f5;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-top: 10rpx;
}

.reply-input-container .reply-textarea {
  width: 100%;
  min-height: 200rpx;
  background-color: white;
  border-radius: 10rpx;
  padding: 10rpx;
  margin-bottom: 10rpx;
}

.reply-input-container .reply-input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reply-input-container .reply-input-footer .text-count {
  color: #999;
  font-size: 24rpx;
}

.reply-input-container .reply-input-footer .submit-btn {
  background-color: #007bff;
  color: white;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
}

.reply-trigger {
  display: inline-flex;
  align-items: center;
  color: #666;
  font-size: 24rpx;
  background-color: #f5f5f5;
  padding: 4rpx 12rpx;
  border-radius: 16rpx;
  cursor: pointer;
}
</style>